package com.lagou.paydemo.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lixingwei
 * @date 2021-01-24 17:18:46
 */
@Configuration
public class RabbitConfig {
    /**
     * 业务队列
     *
     * @return Queue
     */
    @Bean
    public Queue queue() {
        Map<String, Object> props = new HashMap<>();
        //设置消息的生存时间 3s
        props.put("x-message-ttl", 3000);
        //设置队列关联的死信交换器 (当队列中的消息达到ttl后仍未被消费，则存入死信队列)
        props.put("x-dead-letter-exchange", "ex.pay.failed");
        //设置死信交换器绑定的绑定键，如果没有特殊指定，则使用原队列的绑定键
        props.put("x-dead-letter-routing-key", "rk.pay.failed");
        return new Queue("queue.pay", true, false, false, props);
    }

    /**
     * 声明死信队列
     *
     * @return Queue
     */
    @Bean
    public Queue deadQueue() {
        return new Queue("queue.pay.failed", true, false, false);
    }

    /**
     * 声明业务交换器(此处使用直接交换器direct)
     *
     * @return Exchange
     */
    @Bean
    public Exchange exchange() {
        return new DirectExchange("ex.pay", true, false);
    }

    /**
     * 声明死信交换器
     *
     * @return Exchange
     */
    @Bean
    public Exchange deadExchange() {
        return new DirectExchange("ex.pay.failed", true, false);
    }

    /**
     * 绑定业务交换器和业务队列
     *
     * @return Binding
     */
    @Bean
    public Binding binding() {
        return BindingBuilder.bind(queue()).to(exchange()).with("rk.pay").noargs();
    }

    /**
     * 绑定死信队列和死信交换器
     *
     * @return Binding
     */
    @Bean
    public Binding deadBinding() {
        return BindingBuilder.bind(deadQueue()).to(deadExchange()).with("rk.pay.failed").noargs();
    }
}
